//
//  DetailViewController.m
//  YL8G
//
//  Created by gzty1 on 12-8-3.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DetailViewController.h"
#import "CustomNavigationController.h"
#import "ReplyViewController.h"
#import "NoteInfoAdapter.h"
#import "AdMoGoView.h"
#import "ScrollView.h"
#import "CellData.h"
#import "LoginController.h"
#import "NoteInfo+YL8G.h"
#import "PhotoViewController.h"
#import "tyconsts.h"
#import "CellView.h"
#import "CellImageLabelView.h"
#import "AppDelegate.h"

static const int KMenuViewHeight=90;

@implementation DetailViewController

- (id)initWithNoteInfo:(NoteInfo*)noteInfo
{
    self = [super initWithNoteInfo:noteInfo];
    if (self) 
	{
        self.hidesBottomBarWhenPushed=YES;
		fullScreenWhenInit=YES;
		fullScreenEnable=YES;
        backWhenWebViewDraggingDownFromTop_=NO;
		[self initImgDownloadNetworkQueue];
        
        NoteInfo* noteInfo=((NoteInfoAdapter*)detailInfoAdapterBase_).noteInfo;
        isMarked_=[noteInfo isExistInMarks]>=0;
    }
    return self;
}

-(void)switchScreen
{
    [super switchScreen];
    
    self.navigationController.navigationBar.alpha=0.0;
    [self setBottomBarAlpha:1.0];
}

-(void)dealloc
{
    [selectedFontSizeImageView_ release];
    [preventButton_ release];
    [moreMenuView_ release];
    loginController_.delegate=nil;
    [loginController_ release];
    adView_.delegate=nil;
    adView_.adWebBrowswerDelegate = nil;
    [adView_ release];
    [timer_ invalidate];
    [timer_ release];
    [super dealloc];
}

-(void)loadView
{
    [super loadView];
    [self setNavigationTitle:@""];
    
    //样式
    [[webView_ layer] setCornerRadius:0];
}

- (NSString*)getAppKey
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString* appKey = [defaults objectForKey:@"appKey"];
    if (appKey ==nil || [appKey length]<=0)
    {
        return AD_APPKEY;
    }
    return appKey;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [adView_ release];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString* showAd = [defaults objectForKey:@"showAd"];
    if (showAd ==nil || [showAd isEqualToString:@"1"])
    {
        adView_ = [[AdMoGoView alloc] initWithAppKey:[self getAppKey]
                                              adType:AdViewTypeNormalBanner
                                         expressMode:NO
                                  adMoGoViewDelegate:self];
        adView_.adWebBrowswerDelegate = self;
        [self.view addSubview:adView_];
        
        //广告定时
        //[timer_ release];
        //timer_=[[NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(onTimer) userInfo:nil repeats:YES] retain];
        //[self onTimer];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.alpha=1.0;
}

-(void)onTimer
{
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:2.25];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  
    if(adView_.alpha==1.0f)
    {
        adView_.alpha = 0.0f;
	}
    else
    {
        adView_.alpha = 1.0f;
	}
	[UIView commitAnimations];  
}

-(void)onCommentWithContent:(NSString*)content
{
    //login
    if(![LoginController hasLogin])
    {
        if(!loginController_)
        {
            loginController_=[[LoginController alloc] init];
        }
        loginController_.delegate=self;
        
        [loginController_ login];
        
        return;
    }
    
    //ReplyViewController
    ReplyViewController* viewController=[[ReplyViewController alloc] 
                                            initWithNoteInfo:((NoteInfoAdapter*)detailInfoAdapterBase_).noteInfo];
    viewController.postDelegate=self;
	CustomNavigationController* nav = [[CustomNavigationController alloc] initWithRootViewController:viewController];
	nav.navigationBarBgImage=[UIImage imageNamed:@"nav_bg2.png"];
	[self presentModalViewController:nav animated:YES];
	[viewController release];
	[nav release];
    
    //init content
    if(content)
    {
        [viewController addToTextView:content];
    }
}

-(void)showWaitingView
{    
    [DialogUtil showModalWaitingViewWithMessage:@""];
}

-(void)hideWaitingView
{
    [DialogUtil hideWaitingView];
}

-(void)filteCustomImgTagWithMutableString:(NSMutableString*)htmlContent
{
    [super filteCustomImgTagWithMutableString:htmlContent];

    if([htmlContent length]>0)
    {	
        NSString* replacements=@"[发自掌中天涯客户端 ];[消息来自掌中天涯];[发自掌中天涯客户端];本帖发自天涯社区手机客户端";
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString* regular = [defaults objectForKey:@"regular"];
        if (regular!=nil && [regular length]>0)
        {
            replacements=regular;
        }
        
        NSArray* replaceArray=[replacements componentsSeparatedByString:@";"];
        for (NSString* replaceStr in replaceArray) 
        {
            [htmlContent replaceOccurrencesOfString:replaceStr withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[htmlContent length])];
        }
        
        /*
        //custom regex
        NSString* regex=@"\\[.*?自.*?天涯.*?\\]";//[发自掌中天涯客户端 ][消息来自掌中天涯]
        if([htmlContent isMatchedByRegex:regex])
        {
            [htmlContent replaceOccurrencesOfRegex:regex withString:@""];
        }
         */
        
        //去掉尾部空格
        NSString* regex=@"\\s+$";
        if([htmlContent isMatchedByRegex:regex])
        {
            [htmlContent replaceOccurrencesOfRegex:regex withString:@""];
        }
        
        //去掉结尾的空行
        NSString* suffix=@"\n";//@"\n　　"
        int suffixLength=[suffix length];
        if([htmlContent hasSuffix:suffix])
        {
            [htmlContent replaceOccurrencesOfString:suffix withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange([htmlContent length]-suffixLength,suffixLength)];
        }
    }
}

-(void)gotoPhotoViewController:(NSString*)currentImageUrl
{
    NSLog(@"largeImageUrlArray:%@", detailInfoAdapterBase_.largeImageUrlArray);
    NSLog(@"middleImageUrlArray:%@", detailInfoAdapterBase_.middleImageUrlArray);

    PhotoViewController *imageViewController = [[PhotoViewController alloc] initWithImageUrlArray:[NSArray arrayWithObject:currentImageUrl] currentUrl:currentImageUrl];
    imageViewController.title = @"看大图";
    [self.navigationController pushViewController:imageViewController animated:YES];
    [imageViewController release];
}

-(void)hideMoreMenuView
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.30];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  
    
    CGRect frame=CGRectMake(0, getScreenHeight()-kStatusHeight, 320, KMenuViewHeight);
    moreMenuView_.frame=frame;
    
    [UIView commitAnimations]; 
    
    [preventButton_ removeFromSuperview];
}

-(void)showLouzhu
{
    showLouzhuOnly_=!showLouzhuOnly_;
    
    [super hideOrShowNotlouzhu];
}

-(void)onCollect
{
    NoteInfo* noteInfo=((NoteInfoAdapter*)detailInfoAdapterBase_).noteInfo;
    if(!isMarked_)
    {
        BOOL ret=[noteInfo addToMarkRecord];
        if(ret)
        {
            isMarked_=YES;
            [DialogUtil postAlertWithMessage:@"收藏成功"];
        }
        else 
        {
            [DialogUtil postAlertWithMessage:@"收藏失败"];
        }
    }
    else 
    {
        BOOL ret=[noteInfo deleteMarkRecordFromDatabase];
        if(ret)
        {
            isMarked_=NO;
            [DialogUtil postAlertWithMessage:@"取消收藏成功"];
        }
        else 
        {
            [DialogUtil postAlertWithMessage:@"取消收藏失败"];
        }
    }
}

-(void)setFontSizeIndex:(int)index
{
    INSTANCE.setting.iFontSizeIndex=index;
    [INSTANCE.setting save];
    
    NSString* callJsStr=[NSString stringWithFormat:@"setFontSize(\"%d\");",INSTANCE.setting.fontSize]; 
    [webView_ stringByEvaluatingJavaScriptFromString:callJsStr];
}

#pragma mark -
#pragma mark PageBarController
-(void)pageBarController:(PageBarController*)pageBarController didSelectIndex:(int)index selected:(BOOL)selected
{
	switch (index) 
    {
        case 0:
            {
                //返回
                [super onNavigationBackPressed];
            }
            break;
        case 3:
            {
                //更多
                if(!moreMenuView_)
                {
                    const int columnCount=4;
                    const int rowCount=2;
                    
                    NSMutableArray* cellDataArray=[[[NSMutableArray alloc] initWithCapacity:columnCount*2] autorelease];
                    
                    //回复
                    CellData* cellData=[[[CellData alloc] init] autorelease];
                    cellData.iImage=[UIImage imageNamed:@"menu_reply.png"];
                    cellData.iId=0;
                    [cellDataArray addObject:cellData];
                    
                    //只看楼主
                    cellData=[[[CellData alloc] init] autorelease];
                    cellData.iImage=[UIImage imageNamed:@"menu_showlouzhu.png"];
                    cellData.iImageSelected=[UIImage imageNamed:@"menu_showall.png"];
                    cellData.iSelected=isShowLouzhu_;
                    cellData.iKeepSelectedState=YES;
                    cellData.iId=1;
                    [cellDataArray addObject:cellData];
                    
                    //跳页
                    cellData=[[[CellData alloc] init] autorelease];
                    cellData.iImage=[UIImage imageNamed:@"menu_jumppage.png"];
                    //cellData.iLabelText=[NSString stringWithFormat:@"%d",pageBarController_.pageNo];
                    cellData.iLabelTextColor=[UIColor blackColor];
                    cellData.labelOriginOffset=CGPointMake(-14, 0);
                    cellData.iCellLayout=ECellLayout_LabelOnImage;
                    cellData.iId=2;
                    [cellDataArray addObject:cellData];
                    
                    //登录
                    cellData=[[[CellData alloc] init] autorelease];
                    cellData.iImage=[UIImage imageNamed:@"menu_login.png"];
                    cellData.iImageSelected=[UIImage imageNamed:@"menu_logout.png"];
                    cellData.iId=3;
                    [cellDataArray addObject:cellData];
                    
                    //小字号
                    cellData=[[[CellData alloc] init] autorelease];
                    cellData.iImage=[UIImage imageNamed:@"menu_smallfontsize.png"];
                    cellData.iId=4;
                    [cellDataArray addObject:cellData];
                    
                    //中字号
                    cellData=[[[CellData alloc] init] autorelease];
                    cellData.iImage=[UIImage imageNamed:@"menu_middlefontsize.png"];
                    cellData.iId=5;
                    [cellDataArray addObject:cellData];
                    
                    //大字号
                    cellData=[[[CellData alloc] init] autorelease];
                    cellData.iImage=[UIImage imageNamed:@"menu_bigfontsize.png"];
                    cellData.iId=6;
                    [cellDataArray addObject:cellData];
                    
                    //收藏
                    cellData=[[[CellData alloc] init] autorelease];
                    cellData.iImage=[UIImage imageNamed:@"menu_collect.png"];
                    cellData.iImageSelected=[UIImage imageNamed:@"menu_cancelcollect.png"];
                    cellData.iSelected=isMarked_;
                    cellData.iKeepSelectedState=YES;
                    cellData.iId=7;
                    [cellDataArray addObject:cellData];
                    
                    //ScrollView
                    moreMenuView_=[[ScrollView alloc] initWithFrame:CGRectMake(0, getScreenHeight()-kStatusHeight, kScreenWidth, KMenuViewHeight)];
                    [moreMenuView_ setColumns:columnCount rows:rowCount intervalH:0 intervalV:0];
                    [moreMenuView_ setCellArray:cellDataArray delegate:self];
                    [moreMenuView_ setBackgroundColor:[UIColor grayColor]];
                    //[moreMenuView_ setBorderColor:[UIColor blueColor]];
                    [self.view addSubview:moreMenuView_];
                    
                    preventButton_=[[UIButton buttonWithType:UIButtonTypeCustom] retain];
                    preventButton_.frame=webView_.frame;
                    [preventButton_ addTarget:self action:@selector(hideMoreMenuView) forControlEvents:UIControlEventTouchUpInside];
                }
                
                //page num
                CellImageLabelView* jumpCell=(CellImageLabelView*)[moreMenuView_ cellViewAtIndex:2];
                [jumpCell setTitle:[NSString stringWithFormat:@"%d",pageBarController_.pageNo]];
                
                //登录状态
                CellView* loginCell=(CellView*)[moreMenuView_ cellViewAtIndex:3];
                [loginCell setSelected:[LoginController hasLogin]];
                
                //阻止操作层
                [self.view insertSubview:preventButton_ belowSubview:moreMenuView_];
                
                //移动动画
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:0.30];
                [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  
                CGRect frame=CGRectMake(0, getScreenHeight()-kStatusHeight-KMenuViewHeight, 320, KMenuViewHeight);
                moreMenuView_.frame=frame;
                [UIView commitAnimations]; 
                
                //字号指示图片位置
                if(!selectedFontSizeImageView_)
                {
                    selectedFontSizeImageView_=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"menu_selectedfontsize.png"]];
                    [moreMenuView_ addSubview:selectedFontSizeImageView_];
                }
                CGRect rect=selectedFontSizeImageView_.frame;
                rect.origin.x=moreMenuView_.bounds.size.width/4*INSTANCE.setting.iFontSizeIndex+(moreMenuView_.bounds.size.width/4-rect.size.width)/2;
                rect.origin.y=moreMenuView_.bounds.size.height-rect.size.height;
                selectedFontSizeImageView_.frame=rect;
            }
            break;
	}
}

#pragma mark -
#pragma mark CellViewDelegate
-(void)handleCellEvent:(CellView*)aSender cellData:(CellData*)aCellData
{
    switch (aCellData.iId) 
    {
        case 0:
            {
                //回复
                [super onComment];
            }
            break;
        case 1:
            {
                //只看楼主
                [self showLouzhu];
            }
            break;
        case 2:
            {
                //跳页
                [pageBarController_ showNumberSelectActionSheet];
            }
            break;
        case 3:
            {
                //登录
                if([LoginController hasLogin])
                {
                    [LoginController logout];           
                }
                else 
                {
                    if(!loginController_)
                    {
                        loginController_=[[LoginController alloc] init];
                    }
                    loginController_.delegate=nil;
                    [loginController_ login];
                }
            }
            break;
        case 4:
            {
                //小字号
                [self setFontSizeIndex:0];
            }
            break;
        case 5:
            {
                //中字号
                [self setFontSizeIndex:1];
            }
            break;
        case 6:
            {
                //大字号
                [self setFontSizeIndex:2];
            }
            break;
        case 7:
            {
                //收藏
                [self onCollect];
            }
            break;
    }
    
    [self hideMoreMenuView];
}

#pragma mark -
#pragma mark LoginControllerDelegate
-(void)loginControllerSuccess:(LoginController*)loginController
{
   [super onComment];
}

#pragma mark -
#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	switch (buttonIndex) 
    {
        case 0:
            {
                [self onCollect];
            }
            break;
        case 1:
            {
                [super onComment];
            }
            break;
    }
}

#pragma mark -
#pragma mark AdMoGoDelegate delegate 
/*
 返回广告rootViewController
 */
- (UIViewController *)viewControllerForPresentingModalView{
    return self.tabBarController;//返回的对象为adView_的父视图控制器
}

/**
 * 广告开始请求回调
 */
- (void)adMoGoDidStartAd:(AdMoGoView *)adMoGoView{
    NSLog(@"广告开始请求回调");
}
/**
 * 广告接收成功回调
 */
- (void)adMoGoDidReceiveAd:(AdMoGoView *)adMoGoView{
    NSLog(@"广告接收成功回调");
    
    adView_.frame=CGRectMake(0, self.view.frame.size.height-adMoGoView.frame.size.height-[super bottomBarHeight], adView_.frame.size.width, adMoGoView.frame.size.height);
    NSLog(@"%@",NSStringFromCGRect(adMoGoView.frame));
}
/**
 * 广告接收失败回调
 */
- (void)adMoGoDidFailToReceiveAd:(AdMoGoView *)adMoGoView didFailWithError:(NSError *)error{
    NSLog(@"广告接收失败回调");
}
/**
 * 点击广告回调
 */
- (void)adMoGoClickAd:(AdMoGoView *)adMoGoView{
    NSLog(@"点击广告回调");
}
/**
 *You can get notified when the user delete the ad 
 广告关闭回调
 */
- (void)adMoGoDeleteAd:(AdMoGoView *)adMoGoView{
    NSLog(@"广告关闭回调");
}

#pragma mark -
#pragma mark AdMoGoWebBrowserControllerUserDelegate delegate 

/*
 浏览器将要展示
 */
- (void)webBrowserWillAppear{
    NSLog(@"浏览器将要展示");
}

/*
 浏览器已经展示
 */
- (void)webBrowserDidAppear{
    NSLog(@"浏览器已经展示");
}

/*
 浏览器将要关闭
 */
- (void)webBrowserWillClosed{
    NSLog(@"浏览器将要关闭");
}

/*
 浏览器已经关闭
 */
- (void)webBrowserDidClosed{
    NSLog(@"浏览器已经关闭");
}

/*
 浏览器分享
 */
- (void)webBrowserShare:(NSString *)url
{
    NSLog(@"浏览器分享:%@",url);
}

@end
